package handles

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"team-mng-sys/cache"
	"team-mng-sys/models"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	Comment := c.PostForm("comment")
	if title == "" || Comment == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Article{

		Title:   title,
		Comment: Comment,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var article []models.Article
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	var total int64
	models.DB.Model(&models.Article{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  500,
		"msg":   "成功",
		"data":  article,
		"total": total,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var article models.Article
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": article,
	})
	return

}

func Del(c *gin.Context) {
	id := c.PostForm("id")

	var article models.Article
	err := models.DB.Where("id=?", id).Delete(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
